// 用户/权限相关接口
import r from '@/utils/request';
import { type ResponseType } from './types';
import { sm2 } from 'sm-crypto';

enum API {
  getCaptcha = '/auth/getCaptcha', // 获取图形验证码
  publicKey = '/auth/publicKey', // 获取公钥
  login = '/auth/login', // 用户登录
  getListForUser = '/menu/getListForUser', // 获取当前登录用户的权限
  wechat = '/auth/wechat', // 微信扫码code登录
  loginBindWeChat = '/auth/loginBindWeChat' // 登录并绑定微信
}

type GetCaptchaResType = ResponseType<{
  id: string; // 加密过的验证码
  imageCode: string; // 验证码base64图片
}>

export function getCaptchaAPI(): Promise<GetCaptchaResType> {
  return r.get(API.getCaptcha);
}

export function publicKeyAPI(): Promise<ResponseType<string>> {
  return r.get(API.publicKey);
}

interface LoginFormData {
  username: string;
  pwd: string;
  verifyCode: string;
  verifyCodeId: string;
}

// 登录接口的返回值
export type LoginResType = ResponseType<{
  model: {
    username: string;
    photo: string;
    type: number;
  };
  token: string;
  loginLog?: {
    ipAddress?: string;
  };
} | null>

export async function loginAPI(data: LoginFormData): Promise<LoginResType> {
  const { data: publicKey } = await publicKeyAPI();
  return r.post(API.login, {
    ...data,
    pwd: sm2.doEncrypt(data.pwd, publicKey)
  });
}

export interface AuthItem {
  id: number
  name: string;
  icon: string;
  url: string;
  pid: number;
  isButton: 0 | 1;
  children: AuthItem[];
}

type GetListForUserResType = ResponseType<{
  list: AuthItem[];
}>

export function getListForUserAPI(): Promise<GetListForUserResType> {
  return r.get(API.getListForUser);
}



export function wechatAPI(code: string): Promise<any> {
  return r.get(API.wechat, { code });
}
export interface LoginBindWeChatParams {
  username:string;
  pwd:string;
  openId:string
}

export async function loginBindWeChatAPI(data: any): Promise<any> {
  const { data: publicKey } = await publicKeyAPI();
  return r.post(API.loginBindWeChat, {
    ...data,
    pwd: sm2.doEncrypt(data.pwd, publicKey)
  });
}
